﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.OleDb;



namespace SPMigrationOracleUtility
{
    public partial class ExcelSPmigrationManipulate: Form
    {
        public string mapid { get; set; }
        public string mode { get; set; }

        DataTable dt1;
        Collect_Site obj1 = new Collect_Site();
        Business objBus = new Business();
        mapping_calss objMap = new mapping_calss();
        public string ExcelCk;

        
        
        int ListSelectioncnt = 0;
        int Libraryselcount = 0;
        bool srctblchanged = false, desttblchanged = false;
        bool flagMapInit;
        bool flagcgintabl;
        bool flagGv;
        bool cngList;

        OleDbDataAdapter dataAdapter;
        DataTable dt;
        DataSet dataSet;
        public string excelFileName { get; set; }
        public string SiteUrl = Convert.ToString(SPMigrationOracleUtility.Appl.Default.SiteURL);
        public ExcelSPmigrationManipulate()
        {
            InitializeComponent();
        }

        private void ExcelSPmigrationManipulate_Load(object sender, EventArgs e)
        {

            txtUrl.Text = SiteUrl;
            lblDisps.Text = "Excel and SharePoint Mapping Step-1 - Create Mapping Name";
            if (mode == "View")
            {
                pnl_disable();
                btnSave.Text = "Ok";
            }
            
            
            this.Height = 450;
            this.Width = 800;
            objBus.Panel_Prop(pnlMappingInit);
            objBus.Panel_Prop(pnlExcelList);
            objBus.Panel_Prop(pnlSPList);
            objBus.Panel_Prop(pnlMappingFnl);
            objBus.Panel_Prop(pnlIntegrate);
            lblDisps.Text = "Excel and SharePoint Mapping Step-1 - Create Mapping Name";

            objMap.Mapping_List_Retrieve(mapid); // mapping_list
           
            ExcelBindDataEdit(objMap.ExcelfilePath); // Bind Excel Data by using retrieve (query + viewname) fields from Mapping_List
            txtFilePath.Text = objMap.ExcelfilePath;
           
            txtMappingName.Text = objMap.mapname;
            txtMappingDesc.Text = objMap.mapdesc;
            objMap.GetUrl(mapid);


            obj1.GetSubSites(cmbSites, objMap.webUrl);
            if (cmbSites.Items.Count > 0)
            {
                cmbSites.SelectedIndex = 0;
            }

            ListItemPair oweb = (ListItemPair)cmbSites.SelectedItem;
            obj1.GetLists(lstLibList, cmbSites, objMap.webUrl);

            objMap.MappingColumn(mapid,lstLibList, lstMapListLib); // mapping_column lsit

            ListSelectioncnt = objMap.lstTemCnt;
            Libraryselcount = objMap.libTemCnt;

            if (mode == "View")
            { }
            else
            {
                List_Lib_Ck();
            }

            //objMap.mapping_coll_name_bind(dg1, objMap.webUrl, mapid);
            dt = objMap.mapping_coll_name_bind(dg1, objMap.SiteUrl, mapid);
            dt1 = dt;
            flagGv = true;
            //if (gvBind.DataSource == null) { btnNextPnl5.Enabled = false; } else { btnNextPnl5.Enabled = true; }


        }

        private void List_Lib_Ck()
        {

            if (ListSelectioncnt == 0 && Libraryselcount == 1)
            {
                btnListLibAdd.Enabled = true;
            }
            else if (ListSelectioncnt == 1 && Libraryselcount == 0)
            {
                btnListLibAdd.Enabled = true;
            }
            else if (ListSelectioncnt == 2 && Libraryselcount == 0)
            {
                btnListLibAdd.Enabled = false;
            }
            else if (ListSelectioncnt == 1 && Libraryselcount == 1)
            {
                btnListLibAdd.Enabled = false;
            }
            else if (ListSelectioncnt == 0 && Libraryselcount == 0)
            {
                btnListLibRem.Enabled = false;
            }

            Step4Enable();
        }

        private void pnl_disable()
        {

            foreach (Control c in this.Controls)
                foreach (Control ctrl in c.Controls)
                {
                    ctrl.Enabled = false;
                    if (ctrl is Button)
                    {
                        ((Button)ctrl).Enabled = true;
                    }

                }

            btnReadExcel.Enabled = false;
            btnBrowse.Enabled = false;
            btnGo.Enabled = false;
            btnListLibAdd.Enabled = false;
            btnListLibRem.Enabled = false;
            btnCancelPnl5.Visible = false;
            //btnClear.Enabled = false;
            btnAddGrid.Enabled = false;
            gvExceldata.Enabled = true;
            dg1.Enabled = true;

        }
        private void btnBrowse_Click(object sender, EventArgs e)
        {
            //ExcelCk = Convert.ToString(CmbSrcTableName.Text);
            GetFilePathFields();
            


        }

        public void GetFilePathFields()
        {
            this.openFileDialog1.Dispose();
            DialogResult dr = this.openFileDialog1.ShowDialog();
            if (dr == System.Windows.Forms.DialogResult.OK)
            {
                excelFileName = openFileDialog1.FileName;
                FileHelper objHelper = new FileHelper(excelFileName);
                txtFilePath.Clear();
                //txtFilePath.Text = objHelper.DirectoryName + "\\" + objHelper.FileName;
                txtFilePath.Text = excelFileName;
                if (objHelper.Extension == ".xlsx" || objHelper.Extension == ".xls")
                {
                    // MessageBox.Show("Valid File Extension Continue the Process");
                    btnReadExcel.Enabled = true;
                }
                else
                {
                    gvExceldata.DataSource = null;
                    MessageBox.Show(excelFileName + ":   Invalid File Extension");
                    btnReadExcel.Enabled = false;
                    objBus._pnl2Trans(gvExceldata, btnNextPnl2);
                }

                gvExceldata.DataSource = null;
                objBus._pnl2Trans(gvExceldata, btnNextPnl2);
                
            }
            else
            {

            }
            
        }

        private void btnCancelPnl1_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void btnNextPnl1_Click(object sender, EventArgs e)
        {
            lblDisps.Text = "Excel and SharePoint Mapping Step-2 - Select SpreadSheet";
            pnlMappingInit.Hide();
            pnlExcelList.Show();
        }



        private void btnPrevPnl2_Click(object sender, EventArgs e)
        {
            lblDisps.Text = "Excel and SharePoint Mapping Step-1 - Create Mapping Name";
            pnlMappingInit.Show();
            pnlExcelList.Hide();
        }

        private void btnCheckFileType_Click(object sender, EventArgs e)
        {

        }

        private void btnReadExcel_Click(object sender, EventArgs e)
        {
            FileHelper objHelper = new FileHelper(excelFileName);
           
            dg1.DataSource = null;
            dt1.Clear();
            dt.Clear();
            CmbSrcTableName.Items.Clear();
            CmbSrcTableName.Items.Add(objHelper.FileName);
            CmbSrcTableName.SelectedIndex = 0;
            objBus._ExcelData(excelFileName, CmbSrcFieldName, gvExceldata);
            CmbSrcFieldName.SelectedIndex = 0;
            objBus._pnl2Trans(gvExceldata, btnNextPnl2);
            
        }

        public void ExcelBindDataEdit(string spExcel)
        {
            FileHelper objHelper = new FileHelper(spExcel);
            CmbSrcTableName.Items.Add(objHelper.FileName);
            CmbSrcTableName.SelectedIndex = 0;
            objBus._ExcelData(spExcel, CmbSrcFieldName, gvExceldata);
            CmbSrcFieldName.SelectedIndex = 0;
            objBus._pnl2Trans(gvExceldata, btnNextPnl2);
        }

        private void btnNextPnl2_Click(object sender, EventArgs e)
        {
            excelFileName = txtFilePath.Text;
            lblDisps.Text = "Excel and SharePoint Mapping Step-3 - Select SharePoint List/Library";
            pnlExcelList.Hide();
            pnlSPList.Show();
        }

        private void btnPrevPnl3_Click(object sender, EventArgs e)
        {
            lblDisps.Text = "Excel and SharePoint Mapping Step-2 - Select SpreadSheet";
            pnlExcelList.Show();
            pnlSPList.Hide();
        }

        private void btnNextPnl3_Click(object sender, EventArgs e)
        {
           
            lblDisps.Text = "Excel and SharePoint Mapping Step-4 - Excel-SharePoint Mapping Fields";
            pnlMappingFnl.Show();
            pnlSPList.Hide();

            if (flagGv == true)
            {

                if (cngList) // If any changes in the List ,set the value TRUE in btnfwd,btnBwd
                {
                    Pnl4_Tranaction();
                }
                else
                {
                    MappingInit();
                    flagGv = false;
                    ListItemPair li = (ListItemPair)cmbSites.SelectedItem;
                    lblDestSiteName.Text = li.URL;
                    if (dg1.Rows.Count == 0) { btnNextPnl4.Enabled = false; } else { btnNextPnl4.Enabled = true; }
                }
               
            }
            else
            {
                Pnl4_Tranaction();
            }
            


        }

        private void Pnl4_Tranaction()
        {

            ListItemPair li = (ListItemPair)cmbSites.SelectedItem;
            lblDestSiteName.Text = li.URL;



            if (flagMapInit)
            {
                Map_ck_TblView();
                Map_ck_LstLib();
                if (srctblchanged == true || desttblchanged == true)
                {
                    MappingInit();
                    dg1.DataSource = null;
                    AddTableColumn();
                    srctblchanged = false;
                    desttblchanged = false;
                    flagcgintabl = true;
                }
                else
                {
                   
                }
            }
            else
            {
                AddTableColumn();
                MappingInit();
            }

            if (dg1.Rows.Count == 0) { btnNextPnl4.Enabled = false; } else { btnNextPnl4.Enabled = true; }

        }

        public void Map_ck_TblView()
        {
                
                 FileHelper obj = new FileHelper(excelFileName);
                    if (!CmbSrcTableName.Text.Contains((obj.FileName)))
                    {
                    srctblchanged = true;
                    }
    
        }

        public void Map_ck_LstLib()
        {
            try
            {
                foreach (ListItemPair srctblName in lstMapListLib.Items)
                {
                    if (!CmbDestListName.Items.Contains(srctblName))
                        srctblchanged = true;
                }
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message);
            }
            if (lstMapListLib.Items.Count != CmbDestListName.Items.Count)
            {
                desttblchanged = true;
            }

        }

        public void MappingInit()
        {
            CmbDestListName.Items.Clear();
            CmbSrcTableName.Items.Clear();

            CmbDestListName.DisplayMember = "Text";
            foreach (object obj in lstMapListLib.Items)
            {
                CmbDestListName.Items.Add(obj);

            }
            if (CmbDestListName.Items.Count > 0)
                CmbDestListName.SelectedIndex = 0;

            CmbSrcTableName.DisplayMember = "FileName";
            CmbSrcTableName.Items.Add(new FileHelper(excelFileName));

            if (CmbSrcTableName.Items.Count > 0)
                CmbSrcTableName.SelectedIndex = 0;
        }

        public void AddTableColumn()
        {
            dt = new DataTable();
            dt.Columns.Add("SourceTableName", typeof(string));
            dt.Columns.Add("SourceTableColumn", typeof(string));
            dt.Columns.Add("SourceColumnType", typeof(string));
            dt.Columns.Add("DestinationListName", typeof(string));
            dt.Columns.Add("DestinationListColumn", typeof(string));
            dt.Columns.Add("DestinationColumnType", typeof(string));
            dt.Columns.Add("DestinationListTemplate", typeof(string));
            dg1.DataSource = dt;
        }


        private void btnPrevPnl4_Click(object sender, EventArgs e)
        {
            lblDisps.Text = "Excel and SharePoint Mapping Step-3 - Select SharePoint List/Library";
            flagMapInit = true;
            pnlMappingFnl.Hide();
            pnlSPList.Show();
        }

        private void CmbSrcFieldName_SelectedIndexChanged(object sender, EventArgs e)
        {
            ExcelItemPairs objType = (ExcelItemPairs)CmbSrcFieldName.SelectedItem;
            lblSrcFieldName.Text = objType.Type;
        }

        private void btnGo_Click(object sender, EventArgs e)
        {
            cmbSites.Items.Clear();
            obj1.GetSubSites(cmbSites, txtUrl.Text);
            if (cmbSites.Items.Count > 0)
            {
                cmbSites.SelectedIndex = 0;
            }
        }

        private void cmbSites_SelectedIndexChanged(object sender, EventArgs e)
        {
            ListItemPair oweb = (ListItemPair)cmbSites.SelectedItem;
            obj1.GetLists(lstLibList, cmbSites, oweb.URL);
            if (mode == "View")
            {
            }
            else
            {
                clr_MapList();
            }
        }

        private void clr_MapList()
        {
            lstMapListLib.Items.Clear();
            ListSelectioncnt = 0;
            Libraryselcount = 0;
            Step4Enable();
            if (lstLibList.Items.Count > 0)
            {
                btnListLibAdd.Enabled = true;
            }
            else
            {
                btnListLibAdd.Enabled = false;
            }

        }

        public void Step4Enable()
        {
            if (ListSelectioncnt > 0 || Libraryselcount > 0)
            {
                btnNextPnl3.Enabled = true;
                btnListLibRem.Enabled = true;
            }
            else
            {
                btnListLibAdd.Enabled = true;
                btnNextPnl3.Enabled = false;
                btnListLibRem.Enabled = false;
            }
        }

        private void btnListLibAdd_Click(object sender, EventArgs e)
        {
            if (lstLibList.Text == "")
            { MessageBox.Show("Please Select List / Library"); }
            else
            {
                MoveData(lstLibList, lstMapListLib, 1);
                cngList = true;
            }

                
        }

        private void btnListLibRem_Click(object sender, EventArgs e)
        {
            MoveData(lstMapListLib, lstLibList, -1);
            cngList = true;
        }

        public void MoveData(ListBox objListsrc, ListBox objListDest, int val)
        {

            bool adddata1 = false;
            string type1 = "";

            try
            {
                ListItemPair objList = (ListItemPair)objListsrc.SelectedItem;
                if (objList.ListTemplate == Microsoft.SharePoint.Client.BaseType.DocumentLibrary)
                {
                    Libraryselcount = Libraryselcount + val;
                }
                else
                {
                    ListSelectioncnt = ListSelectioncnt + val;
                }

                if (ListSelectioncnt == 0 && Libraryselcount == 1)
                {
                    adddata1 = true;
                    btnListLibAdd.Enabled = true;

                }
                else if (ListSelectioncnt == 1 && Libraryselcount == 0)
                {

                    adddata1 = true;
                    btnListLibAdd.Enabled = true;

                }
                else if (ListSelectioncnt == 2 && Libraryselcount == 0)
                {
                    adddata1 = true;
                    btnListLibAdd.Enabled = false;

                }
                else if (ListSelectioncnt == 1 && Libraryselcount == 1)
                {
                    adddata1 = true;
                    btnListLibAdd.Enabled = false;
                }
                else if (ListSelectioncnt == 0 && Libraryselcount == 0)
                {
                    adddata1 = true;
                   
                }
                else
                {
                    Libraryselcount = 1;
                    MessageBox.Show("Invalid Mapping.");
                }

                if (adddata1)
                {
                    objListDest.Items.Add(objList);
                    objListDest.DisplayMember = "Text";
                    int selectedIndex = Convert.ToInt32(objListsrc.SelectedIndex);
                    objListsrc.Items.RemoveAt(selectedIndex);
                }
            }
            catch (SystemException ex)
            {
                MessageBox.Show("Select the valid List or Library");
            }


            Step4Enable();
        }

        private void CmbDestListName_SelectedIndexChanged(object sender, EventArgs e)
        {
            ListItemPair oweb = (ListItemPair)CmbDestListName.SelectedItem;
            obj1.GetListFields(CmbDestListName, CmbDestFieldName, oweb.URL);
        }

        private void CmbDestFieldName_SelectedIndexChanged(object sender, EventArgs e)
        {
            obj1.GetListFieldType(CmbDestFieldName, lblDestFieldName);
        }


        private void btnAddGrid_Click(object sender, EventArgs e)
        {
            bool exist = false;

            ExcelItemPairs objsrc = (ExcelItemPairs)CmbSrcFieldName.SelectedItem;
            FileHelper objsrcFld = (FileHelper)CmbSrcFieldName.SelectedItem;
            ListItemPair dispName = (ListItemPair)CmbDestListName.SelectedItem;
            DestFieldType intName = (DestFieldType)CmbDestFieldName.SelectedItem;

            foreach (DataRow row in dt.Rows)
            {
                if (Convert.ToString(row["SourceTableName"]) == Convert.ToString(objsrcFld.FileName)
                    && Convert.ToString(row["SourceTableColumn"]) == Convert.ToString(objsrc.Value)
                    && Convert.ToString(row["SourceColumnType"]) == Convert.ToString(lblSrcFieldName.Text)
                    && Convert.ToString(row["DestinationListName"]) == Convert.ToString(dispName.Text)
                    && Convert.ToString(row["DestinationListColumn"]) == Convert.ToString(intName.internalName)
                    && Convert.ToString(row["DestinationColumnType"]) == Convert.ToString(lblDestFieldName.Text)
                    && Convert.ToString(row["DestinationListTemplate"]) == Convert.ToString(dispName.ListTemplate))
                {
                    MessageBox.Show("Duplicate Entry ! Same entry exists ", "Duplication", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    exist = true;
                }

                else if (Convert.ToString(row["DestinationListName"]) == Convert.ToString(dispName.Text) && Convert.ToString(row["DestinationListColumn"]) == Convert.ToString(intName.internalName))
                {
                    MessageBox.Show("Cannot map Destination List Field twice" + System.Environment.NewLine + "'" + row["DestinationListColumn"] + "'  Field already mapped", "Mapping Exist Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    exist = true;
                }
            }

            if (!exist)
            {
                if (string.Equals(lblDestFieldName.Text, "File", StringComparison.CurrentCultureIgnoreCase))
                {
                    DialogResult result = MessageBox.Show("Could you please ensure Source Table field '" + objsrc.SrcName + "' consist URL(Document Path). Since you have selected Document Libray", "Document Library Verification", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning);
                    if (result == DialogResult.OK)
                    {
                        dt.Rows.Add(objsrcFld.FileName, objsrc.Value, lblSrcFieldName.Text, dispName.Text, intName.internalName, lblDestFieldName.Text, Convert.ToString(dispName.ListTemplate));
                        dg1.DataSource = dt;
                    }
                }
                else
                {
                    dt.Rows.Add(objsrcFld.FileName, objsrc.Value, lblSrcFieldName.Text, dispName.Text, intName.internalName, lblDestFieldName.Text, Convert.ToString(dispName.ListTemplate));
                    dg1.DataSource = dt;
                }
            }
            if (dg1.Visible)
            {
                btnNextPnl4.Enabled = true;
            }


        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            if (mode == "View")
            { }
            else
            {
                FileHelper objHelper = new FileHelper(excelFileName);
                objMap.Mapping_List(txtMappingName.Text, txtMappingDesc.Text, "", "", "", mapid, excelFileName);
                objMap.Mapping_Column_List(dt, objMap.SiteUrl, mapid);
                MessageBox.Show("Mapping Updated");
            }
            this.Close();
        }

        private void btnNextPnl4_Click(object sender, EventArgs e)
        {
            lblDisps.Text = "Excel and SharePoint Mapping Step-5 - Excel-SharePoint Mapping Details";
            pnlIntegrate.Show();
            pnlMappingFnl.Hide();
            MappingDetails();
        }

        private void btnPrevPnl5_Click(object sender, EventArgs e)
        {
            lblDisps.Text = "Excel and SharePoint Mapping Step-4 - Excel-SharePoint Mapping Fields";
            pnlIntegrate.Hide();
            pnlMappingFnl.Show();
        }

        private void btnCancelPnl5_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void btnCancelPnl4_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void btnCancelPnl3_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void btnCancelPnl2_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void MappingDetails()
        {
            lblMapName.Text = txtMappingName.Text.ToUpper();
            lblMapDesc.Text = txtMappingDesc.Text.ToUpper();
            lblSrcTblView.Text = "";

            CmbSrcTableName.DisplayMember = "SrcName";
            FileHelper objType = (FileHelper)CmbSrcTableName.SelectedItem;
            lblSrcTblView.Text = objType.FileName;

            lblDestListLib.Text = "";
            foreach (ListItemPair destListName in lstMapListLib.Items)
            {
                string s1 = destListName.Text.ToUpper();
                lblDestListLib.Text = lblDestListLib.Text.ToUpper() +System.Environment.NewLine + s1.ToString();
            }
            lblMapRowCnt.Text = Convert.ToString(dg1.Rows.Count);
            lblSrcRecCnt.Text = Convert.ToString(gvExceldata.Rows.Count); 
        }

        private void pnlMappingInit_MouseMove(object sender, MouseEventArgs e)
        {
            if (txtMappingName.Text == "")
            {
                btnNextPnl1.Enabled = false;
            }
            else
            {
                btnNextPnl1.Enabled = true;
            }
        }

        private void txtMappingName_Leave(object sender, EventArgs e)
        {
            if (txtMappingName.Text == "")
            {
                btnNextPnl1.Enabled = false;
            }
            else
            {
                btnNextPnl1.Enabled = true;
            }
        }

        private void deleteSelectedRowToolStripMenuItem_Click(object sender, EventArgs e)
        {
            DialogResult result = MessageBox.Show("Are you sure you want to Delete the Selected Row ?", "Row Deletion", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
            if (result == DialogResult.Yes)
            {
                dg1.Rows.Remove(dg1.CurrentRow);
            }
            if (dg1.Rows.Count == 0) { btnNextPnl4.Enabled = false; } else { btnNextPnl4.Enabled = true; }
        }

        private void dg1_MouseClick(object sender, MouseEventArgs e)
        {
            if (mode == "View")
            {
            }
            else
            {

                if (e.Button == System.Windows.Forms.MouseButtons.Right)
                {
                    if (dg1.Rows.Count > 0)
                    {
                        contextMenuStrip1.Show(Cursor.Position);
                    }
                }
            }
        }

        private void deleteSelectedRowToolStripMenuItem_Click_1(object sender, EventArgs e)
        {
            DialogResult result = MessageBox.Show("Are you sure you want to Delete the Selected Row ?", "Row Deletion", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
            if (result == DialogResult.Yes)
            {
                dg1.Rows.Remove(dg1.CurrentRow);
            }
            if (dg1.Rows.Count == 0) { btnNextPnl4.Enabled = false; } else { btnNextPnl4.Enabled = true; }
        }

       

    }

}

